package com.cy.util;

import com.alibaba.fastjson.JSON;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by PVer on 2017/7/27.
 */
public class CommonUtil {

    private static Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE );

    /**
     * 获取UUID
     * @return
     */
    public static String getUUID(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * Unicode编码
     * @param dataStr
     * @return
     */
    public static String gbEncoding(final String dataStr) {
        StringBuffer unicode = new StringBuffer();

        for (int i = 0; i < dataStr.length(); i++) {

            // 取出每一个字符
            char c = dataStr.charAt(i);

            // 转换为unicode
            unicode.append("\\u" + Integer.toHexString(c));
        }

        return unicode.toString();
    }

    /**
     * Unicode解码
     * @param dataStr
     * @return
     */
    public static String decodeUnicode(final String dataStr) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }

    public static String toUnicode(Map<String, String> map) throws UnsupportedEncodingException {
        for (Map.Entry<String, String> m : map.entrySet()){
            map.put(m.getKey(), gbEncoding(m.getValue()));
        }
        return JSON.toJSONString(map);
    }

    /**
     * 微信表情
     * @param nike
     * @return
     */
    public static String wx(String nike){
        if(nike == null) return nike;
        Matcher emojiMatcher = emoji.matcher(nike) ;
        if (emojiMatcher.find()){
            return "***" ;
        }
        return nike;
    }

}
